#include "usermanagementwidget.h"
#include "ui_usermanagementwidget.h"
#include "databasehandler.h"
#include "AuditLogger.h"
#include <QMessageBox>
#include <QInputDialog>
#include <QDateTime>
#include <QDebug>
#include <QSqlTableModel>
#include <QSqlRecord>
#include <QAbstractItemView>
#include <QVariantMap>
#include <QCoreApplication>

UserManagementWidget::UserManagementWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserManagementWidget),
    m_userModel(nullptr),
    m_dbHandler(new DatabaseHandler()),
    m_auditLogger(nullptr)
{
    ui->setupUi(this);
    setupUI();
    setupConnections();
    loadUsers();
}

UserManagementWidget::UserManagementWidget(DatabaseHandler *dbHandler, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserManagementWidget),
    m_userModel(nullptr),
    m_dbHandler(dbHandler),
    m_auditLogger(new AuditLogger(dbHandler))
{
    // 初始化审计日志
    if (m_auditLogger && !m_auditLogger->initialize(QCoreApplication::applicationDirPath() + "/audit_trail.db", "secure_password_123")) {
        qCritical() << "[UserManagement] 审计日志初始化失败";
    }

    ui->setupUi(this);
    setupUI();
    setupConnections();
    loadUsers();
}

UserManagementWidget::~UserManagementWidget()
{
    delete ui;
    if (m_auditLogger) {
        delete m_auditLogger;
    }
}

void UserManagementWidget::setupUI()
{
    if (!m_dbHandler) {
        qWarning() << "DatabaseHandler is null";
        return;
    }
    
    m_userModel = new QSqlTableModel(this, m_dbHandler->database());
    m_userModel->setTable("users");
    m_userModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    m_userModel->select();
    
    ui->tableView->setModel(m_userModel);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
}

void UserManagementWidget::setupConnections()
{
    connect(ui->addButton, &QPushButton::clicked, this, &UserManagementWidget::onAddUserClicked);
    connect(ui->deleteButton, &QPushButton::clicked, this, &UserManagementWidget::onDeleteUserClicked);
    connect(ui->refreshButton, &QPushButton::clicked, this, &UserManagementWidget::refreshUserList);
}

void UserManagementWidget::loadUsers()
{
    if (m_userModel) {
        m_userModel->select();
        ui->tableView->resizeColumnsToContents();
    }
}

void UserManagementWidget::refreshUserList()
{
    if (m_userModel) {
        m_userModel->select();
        ui->tableView->resizeColumnsToContents();
    }
}

void UserManagementWidget::onSearchButtonClicked()
{
    // 搜索功能实现
    qDebug() << "搜索按钮被点击";
}

void UserManagementWidget::onAddUserClicked()
{
    if (!m_dbHandler) {
        QMessageBox::warning(this, tr("错误"), tr("数据库处理器未初始化"));
        return;
    }

    QString username = ui->usernameEdit->text();
    QString password = ui->passwordEdit->text();
    QString role = ui->roleComboBox->currentText();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, tr("警告"), tr("用户名和密码不能为空"));
        return;
    }

    if (m_dbHandler->userExists(username)) {
        QMessageBox::warning(this, tr("警告"), tr("用户已存在"));
        return;
    }

    if (m_dbHandler->addUser(username, password, role)) {
        // 记录审计日志
        if (m_auditLogger) {
            AuditEntry entry{
                QDateTime::currentDateTime(),
                "admin", // 临时使用固定用户名，实际应该从会话获取
                "CREATE",
                "users",
                username,
                "用户创建",
                QVariantMap(), // 新建用户无旧值
                QVariantMap({
                    {"username", username},
                    {"role", role}
                }),
                "用户创建"
            };
            m_auditLogger->logEntry(entry);
        }

        // 刷新用户列表
        refreshUserList();

        // 清空输入框
        ui->usernameEdit->clear();
        ui->passwordEdit->clear();
        ui->roleComboBox->setCurrentIndex(0);

        QMessageBox::information(this, tr("成功"), tr("用户添加成功"));
    } else {
        QMessageBox::critical(this, tr("错误"), tr("添加用户失败: %1").arg(m_dbHandler->lastError()));
    }
}

void UserManagementWidget::onEditUserClicked()
{
    QModelIndex index = ui->tableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, tr("警告"), tr("请先选择一个用户"));
        return;
    }
    
    QSqlRecord record = m_userModel->record(index.row());
    QString username = record.value("username").toString();
    QString currentRole = record.value("role").toString();
    
    // 简单的编辑对话框
    bool ok;
    QString newRole = QInputDialog::getItem(this, tr("编辑用户"), 
                                          tr("选择新角色:"), 
                                          QStringList() << "admin" << "operator" << "viewer",
                                          0, false, &ok);
    
    if (ok && !newRole.isEmpty() && newRole != currentRole) {
        QVariantMap oldData = {
            {"username", username},
            {"role", currentRole}
        };
        
        QVariantMap newData = {
            {"username", username},
            {"role", newRole}
        };
        
        // 执行数据库更新
        m_userModel->setData(index.sibling(index.row(), m_userModel->fieldIndex("role")), newRole);
        if (m_userModel->submitAll()) {
            // 记录审计日志
            logUserChange("UPDATE", oldData, newData, "角色更新");
            QMessageBox::information(this, tr("成功"), tr("用户角色更新成功"));
        } else {
            QMessageBox::critical(this, tr("错误"), tr("更新用户失败"));
        }
    }
}

void UserManagementWidget::onDeleteUserClicked()
{
    QModelIndex index = ui->tableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, tr("警告"), tr("请先选择一个用户"));
        return;
    }
    
    QSqlRecord record = m_userModel->record(index.row());
    QString username = record.value("username").toString();
    
    // 确认删除
    int reply = QMessageBox::question(this, tr("确认删除"),
                                   tr("确定要删除用户 '%1'?").arg(username),
                                   QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        QVariantMap oldData = {
            {"username", username},
            {"role", record.value("role").toString()}
        };
        
        // 从数据库删除用户
        m_userModel->removeRow(index.row());
        if (m_userModel->submitAll()) {
            // 记录审计日志
            logUserChange("DELETE", oldData, QVariantMap(), "用户删除");
            
            // 刷新用户列表
            refreshUserList();
            QMessageBox::information(this, tr("成功"), tr("用户删除成功"));
        } else {
            QMessageBox::critical(this, tr("错误"), tr("删除用户失败"));
        }
    }
}

void UserManagementWidget::logUserChange(const QString& action, 
                                       const QVariantMap& oldData,
                                       const QVariantMap& newData,
                                       const QString& reason)
{
    if (!m_auditLogger) {
        qWarning() << "审计日志器未初始化";
        return;
    }
    
    AuditEntry entry{
        QDateTime::currentDateTime(),
        "admin", // 临时使用固定用户名，实际应该从会话获取
        action,
        "users",
        oldData.value("username", newData.value("username")).toString(),
        "用户管理操作",
        oldData,
        newData,
        reason
    };
    
    m_auditLogger->logEntry(entry);
}